<template>
  <div class="upload">
    <el-card class="box-card">
      <div class="file-button">
        <span>上传文件</span>
        <input type="file" class="file-upload" @change="uploadFile">
      </div>
      <div class="info" v-for="value,index in filterData">
        <div class="file-name">{{value.originalFileName}}</div>
        <div class="file-size">{{value.fileSize}}</div>
        <div class="file-process">
          <progress id="pro" v-bind:value="value.demo"></progress>
        </div>
        <div style="float: left; width:8%">
          <img src="../image/sure.png" v-bind:style="{display:value.flag ==4 ? 'initial' : 'none'}">
          <div v-bind:style="{display:value.flag ==3 ? 'initial' : 'none'}" style="float: right;line-height: 16px;font-size: 13px;">已取消</div>
        </div>
        <div class="file-operate" v-bind:style="{display:value.flag==4 || value.flag==3 ? 'none' : 'initial' }">
          <img src="../image/pause.png" @click="pause(value.formData[0].file_name)"
               v-bind:class="{ operate_hidden : value.flag==2,operate_show: value.flag ==1}" >
          <img src="../image/continue.png"  @click="start(value.formData[0].file_name)"
               v-bind:class="{ operate_hidden : value.flag==1,operate_show: value.flag ==2}">
          <img src="../image/del.png" @click="stop(value.formData[0].file_name)"
               v-bind:class="{operate_show: value.flag==1,operate_show: value.flag==2}">
        </div>
      </div>
    </el-card>

  </div>
</template>

<script>
  let dataArray = [];
  let work = new Map();
  // flag 1: 正在上传  2：暂停上传 3 ：取消上传 4： 上传成功
  export default {
    name: 'Upload',
    data(){
      return {
        dataArray:dataArray
      }
    },
    computed:{
      filterData:function(){
        let data = this.dataArray;
        return data.filter(function(value){
          return value.demo = (value.formData.length-value.formDataQueue.length)/value.formData.length +"";
        })
      }
    },
    methods: {
      start : function(data){
        let the = this;
        console.log('开始上传'+data)
        dataArray.forEach(function(item,index,array){
          if(item.formData[0].file_name == data){
            item.flag =1;
            the.$options.methods.workUtil(index);
            return ;
          }
        })
      },
      pause : function(data){
        dataArray.forEach(function(item,index,array){
          if(item.formData[0].file_name == data){
            item.flag =2;
            return ;
          }
        })
        console.log('暂停上传'+data)
        work.get(data).terminate();
        work.delete(data);
      },
      stop : function(data){
        dataArray.forEach(function(item,index,array){
          if(item.formData[0].file_name == data){
            item.flag =3;
            return ;
          }
        })
        console.log('停止上传'+data)
        if(work.get(data)!=undefined){
          work.get(data).terminate();
          work.delete(data);
        }
      },
      uploadFile: function () {
        let fileStream = document.querySelector('.file-upload').files[0]
        if (fileStream === undefined) {
          return
        }
        let data = {}
        data.formData = []
        data.formDataQueue = new Array()
        data.originalFileName = fileStream.name;
        data.fileSize = this.$options.methods.displayFileSize(fileStream.size);
        data.flag =1;//上传标记符
        let segment = 5;//段大小
        var chunk = parseInt(fileStream.size / segment) //计算出每片大小
        var chunks = [];
        var start = 0;
        //文件分片
        for (let i = 0; i < segment; i++) {
          let end = start + chunk;
          chunks[i] = new Object();
          chunks[i].start = start;
          //如果是最后一段，则到最后段
          if (i == (segment - 1)) {
            chunks[i].end = fileStream.size
          } else {
            chunks[i].end = end;
          }
          chunks[i].blob = fileStream.slice(chunks[i].start, chunks[i].end);
          chunks[i].start = start;
          start = end;
        }

        //对文件名进行重命名
        let originalnameArr = fileStream.name.split('.')
        let postfix = originalnameArr[originalnameArr.length - 1]
        let file_name = Date.now() + (parseInt(Math.random() * 1000000) + "." + postfix)

        for (let i = 0; i < chunks.length; i++) {
          data.formData[i] = []
          data.formData[i].file_name = file_name
          data.formData[i].start = chunks[i].start
          data.formData[i].end = chunks[i].end
          data.formData[i].file = chunks[i].blob, i + fileStream.name
          data.formDataQueue.push(data.formData[i])
        }

        dataArray.push(data)
        this.$options.methods.workUtil(dataArray.length-1)

      },
      workUtil: function(data){//data 表示 数组下标
        let worker = new Worker('src/util/upload.js')
        worker.onmessage = function (event) {

          let arr = dataArray[data];
          arr.formDataQueue.shift()

          if(arr.formDataQueue.length === 0 || arr.formDataQueue === undefined){
            arr.flag =4;
            work.get(event.data).terminate();
            return
          }
          worker.postMessage(dataArray[data].formDataQueue[0])
        }
        worker.postMessage(dataArray[data].formDataQueue[0])
        work.set(dataArray[data].formDataQueue[0].file_name,worker);
      },
      displayFileSize: function (size) {
        let KB = 1024;
        let MB = KB * 1024;
        let GB = MB * 1024;
        if (size >= GB) {
          return Math.round(parseFloat(size/GB)*100)/100+"GB"
        } else if (size >= MB) {
          return Math.round(parseFloat(size/MB)*100)/100+"MB"
        } else if (size >= KB) {
          return Math.round(parseFloat(size/KB)*100)/100+"KB"
        } else {
          return Math.round(parseFloat(size/GB)*100)/100+"KB"
        }
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .box-card{width:1100px;height: 500px;border: 1px solid #3091F2;margin: 0 auto;text-align: left;position: relative;}

  .info{
    margin-top: 10px;
    width: 100%;
    height: 25px;
    width: 500px;
    border-bottom: 1px #d8dce5 solid;
  }
  .file-name{
    position: relative;
    float: left;
    width: 25%;
    display: block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    line-height: 16px;
  }
  .file-size{
    float: left;
    width: 15%;
  }
  .file-process{
    float: left;
    width: 38%;
  }
  .file-operate{
    width: 14%;
    float: left;
  }
  .operate_hidden{
    display: none;
  }
  .operate_show{
    display: initial;
  }
  .file-button{
    position: relative;
    width: 80px;
    background: #2d8cf0;
    color: #FFF;
    border-radius: 2px;
    text-align: center;
    padding: 5px;
  }
  .file-button:hover {
    background: #57a3f3;
  }
  .file-upload{
     display: block;
     position: absolute;
     opacity: 0;
     top: 0;
     left: 0;
     width: 100%;
   }

</style>
